<template>
  <div class="slider" ref="slide">
    <div class="slider-group" ref = "slideGroup">
      <slot></slot>
    </div>
    <div class="dots">
      <span class="dot" :class="{active: currentIndex === index }" v-for="(item, index) in dots" :key = 'index'></span>
    </div>
  </div>
</template>

<script>
import BScroll from '@better-scroll/core'
import Slide from '@better-scroll/slide'
BScroll.use(Slide)
import {addClass} from 'commom/js/dom.js'
export default {
  data(){
    return{
      dots:[],
      currentIndex:0
    }
  },
  created(){
  },
  mounted(){
    setTimeout(() => {
      this._setSlideWidth()
      this._initDots()
      this._initSlider()
    }, 20)
    window.addEventListener('resize',function(){
      this._setSlideWidth();
      this.slider.refresh();
    })
  },
  methods:{
    _setSlideWidth(){
      this.children = this.$refs.slideGroup.children;
      
      let width = 0;
      let slidewidth = this.$refs.slide.clientWidth;
      for(var i = 0;i<this.children.length;i++){
        let child = this.children[i];
        addClass(child,'slider-item');
        child.style.width = slidewidth +'px'
        width += slidewidth;
      }
      this.$refs.slideGroup.style.width = width+'px';
    },
    _initSlider(){
      this.slider = new BScroll(this.$refs.slide,{
        scrollX: true,
        scrollY: false,
        slide: {
          threshold: 100,
          loop: true,
          autoplay:true
        },
        momentum: false,
        bounce: false,
        stopPropagation: true
      })
      this.slider.on('slideWillChange', (page) => {
        this.currentIndex = page.pageX;
      })
    },
    _initDots(){
      this.dots = new Array(this.children.length);
    }
  }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~commom/stulys/variable.styl"
  .slider
    min-height: 1px
    position: relative;
    .slider-group
      position: relative
      overflow: hidden
      white-space: nowrap
      .slider-item
        float: left
        box-sizing: border-box
        overflow: hidden
        text-align: center
        a
          display: block
          width: 100%
          overflow: hidden
          text-decoration: none
        img
          display: block
          width: 100%
    .dots
      position :absolute;
      right :0;
      left  :0;
      bottom :12px;
      text-align :center;
      font-size :0;
      .dot
        display :inline-block;
        width: 8px;
        height: 8px;
        border-radius :50%;
        margin: 0 4px;
        background-color: $color-text-l;
        transition :all .2s ease;
        &.active
          background-color: $color-text-ll;
          width: 18px
          border-radius: 5px
</style>

